package cn.gailvlun.gll.presentation.apartment

import android.arch.lifecycle.ViewModelProviders
import android.content.Context
import android.content.Intent
import android.databinding.DataBindingUtil
import android.os.Bundle
import cn.gailvlun.gll.R
import cn.gailvlun.gll.bean.PlaceHolder
import cn.gailvlun.gll.databinding.ActivityOpenSigningBinding
import cn.gailvlun.gll.net.HttpMethods
import cn.gailvlun.gll.net.HttpSubscriber
import cn.gailvlun.gll.net.apartment.room.GoLiveRoomReq
import cn.gailvlun.gll.net.apartment.room.Room
import cn.gailvlun.gll.net.apartment.room.StartRoomReq
import cn.gailvlun.gll.presentation.base.BaseActivity
import cn.gailvlun.gll.util.DateUtil
import cn.gailvlun.gll.util.DialogUtil
import cn.gailvlun.gll.util.RxUtil
import cn.gailvlun.gll.util.ToastUtil
import cn.gailvlun.gll.widget.dialog.DatePickerDialog
import org.joda.time.DateTime

class OpenSigningActivity : BaseActivity() {

    companion object {
        fun openActivity(context: Context, roomId: Int) {
            val intent = Intent(context, OpenSigningActivity::class.java)
            intent.putExtra("roomId", roomId)
            context.startActivity(intent)
        }
    }

    private lateinit var mBinding: ActivityOpenSigningBinding

    override fun initComponent() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_open_signing)
        mBinding.presenter = Presenter()
    }

    override fun createHandler() {
        mBinding.nbv.setOnBackListener {
            onBackPressed()
        }
        mBinding.nbv.setOnMenuClickListener {
            if (mBinding.startTime == null || mBinding.closeTime == null || mBinding.startSignTime == null) {
                ToastUtil.showShort("请选择时间")
                return@setOnMenuClickListener
            }

            val pd = DialogUtil.showIndeterminate(mContext)

            val req = GoLiveRoomReq().apply {
                this.room_id = roomId!!
                this.start_date_time = mBinding.startTime!!.millis / 1000
                this.close_date_time = mBinding.closeTime!!.millis / 1000
                this.apply_date_time = mBinding.startSignTime!!.millis / 1000
            }
            HttpMethods.getRoomService()
                    .goLiveRoom(req)
                    .compose(RxUtil.applyScheduler())
                    .compose(bindToLifecycle())
                    .subscribe(object : HttpSubscriber<Room>() {
                        override fun onSuccess(response: Room?) {
                            ToastUtil.showShort("已开启上线")
                            finish()
                        }

                        override fun onFailure(errMsg: String?, response: Room?, code: Int) {
                            DialogUtil.showError(mContext, errMsg)
                        }

                        override fun onFinish() {
                            super.onFinish()
                            pd.dismiss()
                        }
                    })

//            HttpMethods.getRoomService()
//                    .startRoom(StartRoomReq(roomId!!, mBinding.startTime, mBinding.closeTime))
//                    .compose(RxUtil.applyScheduler())
//                    .compose(bindToLifecycle())
//                    .subscribe(object : HttpSubscriber<PlaceHolder>() {
//                        override fun onSuccess(response: PlaceHolder?) {
//                            ToastUtil.showShort("报名开启成功")
//                            finish()
//                        }
//
//                        override fun onFailure(errMsg: String?, response: PlaceHolder?, code: Int) {
//                            DialogUtil.showError(mContext, errMsg)
//                        }
//
//                        override fun onFinish() {
//                            super.onFinish()
//
//                            pd.dismiss()
//                        }
//                    })
        }
    }

    private var roomId: Int? = null
    private lateinit var mViewModel: OpenSigningViewModel
    private var room: Room? = null

    override fun loadData(savedInstanceState: Bundle?) {
        roomId = intent.getIntExtra("roomId", -1)
        mViewModel = ViewModelProviders.of(this).get(OpenSigningViewModel::class.java)
        if (roomId == -1) {
            finish()
        } else {
            if (roomId != null) {
                room = mViewModel.getRoomById(roomId!!)
            }
        }
    }

    inner class Presenter {
        fun onStartTime() {
            val initTime = DateTime.now().withMinuteOfHour(0).withSecondOfMinute(0)
                    .withMillisOfSecond(0).plusHours(1)

            val dpd = DatePickerDialog(mContext)
            dpd.setTitle("正式开启时间")
            dpd.setFirstNotComplete(initTime, initTime.plusYears(1))
            dpd.setSelectDate(mBinding.startTime)
            dpd.setSelectTime(mBinding.startTime)
            dpd.setOnConfirmListener { _, data ->
                mBinding.startTime = data
                mBinding.closeTime = data.plusMillis((room!!.close_datetime.time - room!!.start_datetime.time).toInt())
                mBinding.invalidateAll()
            }
            dpd.show()
        }
        
        fun onCloseTime() {
            if (mBinding.startTime == null) {
                ToastUtil.showShort("请先选择房间正式开启时间")
                return
            }
            val dpd = DatePickerDialog(mContext)
            dpd.setTitle("房间关闭时间")
            dpd.setFixDate(mBinding.startTime!!.plusDays(room?.tasks?.size!!))
            dpd.setRangeHourFixMinute(20, 23, 0)
            dpd.setSelectDate(mBinding.closeTime)
            dpd.setSelectTime(mBinding.closeTime)
            dpd.setOnConfirmListener { dialog, data ->
                mBinding.closeTime = data
                mBinding.invalidateAll()
            }
            dpd.show()
        }

        fun onSignStartTime() {
            val initTime = DateTime.now().withMinuteOfHour(0).withSecondOfMinute(0)
                    .withMillisOfSecond(0).plusHours(1)

            val dpd = DatePickerDialog(mContext)
            dpd.setTitle("开始报名时间")
            dpd.setFirstNotComplete(initTime, initTime.plusYears(1))
            dpd.setSelectDate(mBinding.startSignTime)
            dpd.setSelectTime(mBinding.startSignTime)
            dpd.setOnConfirmListener { _, data ->
                mBinding.startSignTime = data
                mBinding.invalidateAll()
            }
            dpd.show()
        }
    }

    object Util {
        @JvmStatic
        fun getStartTime(startTime: DateTime?): String? {
            if (startTime == null) {
                return null
            }
            return DateUtil.format(DateUtil.NO_SECOND_PATTERN, startTime.toDate())
        }

        @JvmStatic
        fun getCloseTime(closeTime: DateTime?): String? {
            if (closeTime == null) {
                return null
            }
            return DateUtil.format(DateUtil.NO_SECOND_PATTERN, closeTime.toDate())
        }

        @JvmStatic
        fun getStartSignTime(startSignTime: DateTime?): String? {
            if (startSignTime == null) {
                return null
            }
            return DateUtil.format(DateUtil.NO_SECOND_PATTERN, startSignTime.toDate())
        }
    }
}